package com.castle.fortress.admin.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.cms.dto.CmsTemplateDto;
import com.castle.fortress.admin.cms.entity.CmsTemplateEntity;
import com.castle.fortress.admin.cms.mapper.CmsTemplateMapper;
import com.castle.fortress.admin.cms.service.CmsTemplateService;
import com.castle.fortress.admin.utils.PicUtil;
import com.castle.fortress.admin.utils.ResourceUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.utils.ConvertUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * cms模板管理表 服务实现类
 *
 * @author castle
 * @since 2022-02-28
 */
@Service
public class CmsTemplateServiceImpl extends ServiceImpl<CmsTemplateMapper, CmsTemplateEntity> implements CmsTemplateService {
    @Value("${castle.cms.templatePath}")
    private String templatePath;
    /**
    * 获取查询条件
    * @param cmsTemplateDto
    * @return
    */
    public QueryWrapper<CmsTemplateEntity> getWrapper(CmsTemplateDto cmsTemplateDto){
        QueryWrapper<CmsTemplateEntity> wrapper= new QueryWrapper();
        if(cmsTemplateDto != null){
            CmsTemplateEntity cmsTemplateEntity = ConvertUtil.transformObj(cmsTemplateDto,CmsTemplateEntity.class);
            wrapper.like(StrUtil.isNotEmpty(cmsTemplateEntity.getTitle()),"title",cmsTemplateEntity.getTitle());
            wrapper.like(cmsTemplateEntity.getStatus() != null,"status",cmsTemplateEntity.getStatus());
        }
        wrapper.orderByAsc("create_time");
        return wrapper;
    }


    @Override
    public IPage<CmsTemplateDto> pageCmsTemplate(Page<CmsTemplateDto> page, CmsTemplateDto cmsTemplateDto) {
        QueryWrapper<CmsTemplateEntity> wrapper = getWrapper(cmsTemplateDto);
        Page<CmsTemplateEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<CmsTemplateEntity> cmsTemplatePage=baseMapper.selectPage(pageEntity,wrapper);
        Page<CmsTemplateDto> pageDto = new Page(cmsTemplatePage.getCurrent(), cmsTemplatePage.getSize(),cmsTemplatePage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(cmsTemplatePage.getRecords(),CmsTemplateDto.class));
        return pageDto;
    }


    @Override
    public List<CmsTemplateDto> listCmsTemplate(CmsTemplateDto cmsTemplateDto){
        QueryWrapper<CmsTemplateEntity> wrapper = getWrapper(cmsTemplateDto);
        List<CmsTemplateEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,CmsTemplateDto.class);
    }

    /**
     * 同步模板信息
     */
    @Override
    public void sycnTemp(){
        List<Map<String,String>> templates =  ResourceUtil.filterDir(templatePath);
        List<CmsTemplateEntity>  olds = baseMapper.selectList(null);
        List<CmsTemplateEntity> newTemp = new ArrayList<>();
        for(Map<String,String> m:templates){
            CmsTemplateEntity d = new CmsTemplateEntity();
            d.setTitle(m.get("fileName"));
            d.setCoverPath("/cmscoverpng/"+d.getTitle()+"/cover.png");
            d.setStatus(YesNoEnum.NO.getCode());
            d.setCreateTime(new Date());
            newTemp.add(d);
        }
        List<CmsTemplateEntity> adds = new ArrayList<>();
        List<CmsTemplateEntity> exist = new ArrayList<>();
        for(CmsTemplateEntity n:newTemp){
            boolean flag = false;
            for(CmsTemplateEntity o:olds){
                if(n.getTitle().equals(o.getTitle())){
                    flag = true;
                    exist.add(o);
                    break;
                }
            }
            if(!flag){
                adds.add(n);
            }
        }
        olds.removeAll(exist);
        //删除无效的模板
        if(!olds.isEmpty()){
            List<Long> ids = new ArrayList<>();
            olds.forEach(item->{
                ids.add(item.getId());
            });
            removeByIds(ids);
        }
        if(!adds.isEmpty()){
            saveBatch(adds);
        }
    }

    @Override
    public RespBody<String> upload(MultipartFile file, String title, String dirPath) {
        String path= "/".equals(dirPath)?"":dirPath ;
        File targetFile = new File(templatePath+ File.separator+title+path+File.separator+file.getOriginalFilename());
        ByteArrayInputStream bis=null;
        try {
            byte[] bytes= null;
            if(com.castle.fortress.common.utils.FileUtils.isImage(file)){
                bytes = PicUtil.compressPic(file,12,350);
            }else{
                bytes = file.getBytes();
            }
            bis= new ByteArrayInputStream(bytes);
            FileUtils.copyToFile(bis, targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
        }
        return RespBody.data("保存成功");
    }

    @Override
    public CmsTemplateDto getActiveTemp() {
        CmsTemplateDto cmsTemplateDto = new CmsTemplateDto();
        cmsTemplateDto.setStatus(YesNoEnum.YES.getCode());
        List<CmsTemplateDto> list =listCmsTemplate(cmsTemplateDto);
        if(list==null || list.size()!= 1){
            throw new BizException(BizErrorCode.CMS_TEMP_ERROR);
        }
        return list.get(0);
    }

    @Override
    public void closeAll() {
        baseMapper.closeAll();
    }
}

